package com.qunar.tech.team12.shell.command.impl;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.qunar.tech.team12.shell.command.annotation.Cmd;
import com.qunar.tech.team12.shell.command.annotation.Opt;
import com.qunar.tech.team12.shell.exception.ShellException;
import com.qunar.tech.team12.shell.io.Input;
import com.qunar.tech.team12.shell.io.impl.ParamInput;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by mzy on 14-7-23.
 */
@Cmd(name = "cat")
public class Cat {

    @Opt(shortName = "default", description = "查看文件")
    public String catFile(Input input) throws ShellException {
        List<String> params = input.read();
        if (params.isEmpty()) {
            throw new ShellException("missing option");
        }
        if (input instanceof ParamInput) {
            String fileName = input.read().get(0);
            try {
                return Files.toString(new File(fileName), Charsets.UTF_8);
            } catch (IOException e) {
                throw new ShellException(fileName + "doesn't exist or not a normal file");
            }
        } else {
            return catString(input.read());
        }
    }

    private String catString(List<String> read) {
        StringBuffer sb = new StringBuffer();
        for (String str : read) {
            sb.append(str);
        }
        return sb.toString();
    }
}
